package cn.ultrarisk.scadmin.manager.web.controller.collection;

import cn.ultrarisk.scadmin.manager.biz.solr.dao.SolrCollectionDAO;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrCollection;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.dao.ZkNodeDAO;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.entity.ZkNode;
import cn.ultrarisk.scadmin.manager.biz.zookeeper.service.ZkNodeService;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import cn.ultrarisk.scadmin.manager.web.dto.solr.SolrConfigDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * OverviewController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/4/17
 * @since V1.0
 */
@Controller
@RequestMapping(value = "/collection/{id}/file")
public class FileController extends BaseController {
    @Autowired
    private SolrCollectionDAO solrCollectionDAO;
    @Autowired
    private ZkNodeDAO zkNodeDAO;
    @Autowired
    private ZkNodeService zkNodeService;

    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<List<ZkNode>> list(@PathVariable("id") Integer id) {
        SolrCollection collection = solrCollectionDAO.get(id, SolrCollection.CONFIG);
        List<String> likePaths = new ArrayList<String>();
        likePaths.add(collection.getConfig());
        likePaths.add(collection.getConfig() + "/%");
        List<ZkNode> configNodes = zkNodeDAO.findByLikePaths(likePaths, 0, true, ZkNode.ID, ZkNode.PARENT_ID, ZkNode.PATH);
        return getOkResponseEntity(configNodes);
    }

    @ResponseBody
    @RequestMapping(value = "/{nodeId}", method = RequestMethod.GET)
    public ResponseEntity<ZkNode> get(@PathVariable("id") Integer id, @PathVariable("nodeId") Integer nodeId) {
        ZkNode node = zkNodeDAO.get(nodeId);
        return getOkResponseEntity(node);
    }

    @ResponseBody
    @RequestMapping(value = "/{nodeId}", method = RequestMethod.POST)
    public ResponseEntity<String> update(@PathVariable("id") Integer id, @PathVariable("nodeId") Integer nodeId, @RequestBody SolrConfigDTO dto) {
        zkNodeService.updateData(nodeId, dto.getData());
        return getOkResponseEntity();
    }
}